﻿#include "device_console.h"
#include "ui_device_console.h"

Device_Console::Device_Console(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Device_Console)
{
    ui->setupUi(this);
    this->setWindowIcon(QIcon(":/new/prefix1/w4.png"));
    this->setWindowTitle("智能家居控制台");
    //创建线程，用于DeviceServer TCP通信
    QThread *deviceThread = new QThread(this);
    device_TCP = new TCP_Thread;
    device_TCP->moveToThread(deviceThread);
    deviceThread->start();

    //创建线程，用于AlarmServer TCP通信
    QThread *alarmThread = new QThread(this);
    alarm_TCP = new TCP_Thread;
    alarm_TCP->moveToThread(alarmThread);
    alarmThread->start();

    //创建线程，用于MediaServer TCP通信
    QThread *mediaThread = new QThread(this);
    media_TCP = new TCP_Thread;
    media_TCP->moveToThread(mediaThread);
    mediaThread->start();

    //建立设备清单界面
    deviceListModel = new QStandardItemModel(this);
    ui->deviceChooseView->setModel(deviceListModel);
    ui->deviceChooseView->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑
    ui->deviceChooseView->setSelectionMode(QAbstractItemView::ExtendedSelection);//只可单选
    ui->deviceChooseView->setShowGrid(false); //设置不显示格子线
    ui->deviceChooseView->setSelectionBehavior(QAbstractItemView::SelectRows);  //设置>选择行为时每次选择一行
    ui->deviceChooseView->setFocusPolicy(Qt::NoFocus);
    ui->deviceChooseView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);//设置表格列宽
    ui->deviceChooseView->verticalHeader()->setVisible(false); //隐藏列表头
    ui->deviceChooseView->horizontalHeader()->setVisible(false); //隐藏行表头
    //建立报警清单
    airAlarmModel = new QStandardItemModel(this);
    ui->listView_airAlarm->setModel(airAlarmModel);
    ui->listView_airAlarm->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑
    ui->listView_airAlarm->setSelectionMode(QAbstractItemView::ExtendedSelection);//只可单选
    ui->listView_airAlarm->setShowGrid(false); //设置不显示格子线
    ui->listView_airAlarm->setSelectionBehavior(QAbstractItemView::SelectRows);  //设置>选择行为时每次选择一行
    ui->listView_airAlarm->setFocusPolicy(Qt::NoFocus);
    ui->listView_airAlarm->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);//设置表格列宽
    ui->listView_airAlarm->verticalHeader()->setVisible(false); //隐藏列表头
    ui->listView_airAlarm->horizontalHeader()->setVisible(false); //隐藏行表头

    refAlarmModel = new QStandardItemModel(this);
    ui->listView_refAlarm->setModel(refAlarmModel);
    ui->listView_refAlarm->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑
    ui->listView_refAlarm->setSelectionMode(QAbstractItemView::ExtendedSelection);//只可单选
    ui->listView_refAlarm->setShowGrid(false); //设置不显示格子线
    ui->listView_refAlarm->setSelectionBehavior(QAbstractItemView::SelectRows);  //设置>选择行为时每次选择一行
    ui->listView_refAlarm->setFocusPolicy(Qt::NoFocus);
    ui->listView_refAlarm->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);//设置表格列宽
    ui->listView_refAlarm->verticalHeader()->setVisible(false); //隐藏列表头
    ui->listView_refAlarm->horizontalHeader()->setVisible(false); //隐藏行表头

    //控制台设定
    buttonGroupSwitch =new QButtonGroup(this);
    buttonGroupSwitch->addButton(ui->radioButton_on,0);
    buttonGroupSwitch->addButton(ui->radioButton_off,1);
    ui->radioButton_on->setChecked(true);
    buttonGroupMode =new QButtonGroup(this);
    buttonGroupMode->addButton(ui->radioButton_cold,0);
    buttonGroupMode->addButton(ui->radioButton_hot,1);
    ui->radioButton_cold->setChecked(true);
    buttonGroupWind =new QButtonGroup(this);
    buttonGroupWind->addButton(ui->radioButton_low,0);
    buttonGroupWind->addButton(ui->radioButton_middle,1);
    buttonGroupWind->addButton(ui->radioButton_high,2);
    ui->radioButton_low->setChecked(true);
    ui->spinBox_temp->setValue(26);
    ui->spinBox_temp->setMaximum(30);
    ui->spinBox_temp->setMinimum(15);

    ui->spinBox_freshTemp->setValue(0);
    ui->spinBox_freshTemp->setMaximum(8);
    ui->spinBox_freshTemp->setMinimum(0);
    ui->spinBox_freezeTemp->setValue(0);
    ui->spinBox_freezeTemp->setMaximum(0);
    ui->spinBox_freezeTemp->setMinimum(-15);

    //建立监控播放器
    refPlayer = new QMediaPlayer;
    refVideoWidget = new QVideoWidget(this);
    ui->playerShow->addWidget(refVideoWidget);
    refVideoWidget->setMaximumSize(QSize(250,160));
    refVideoWidget->setMinimumSize(QSize(250,160));
    refPlayer->setVideoOutput(refVideoWidget);
    refVideoWidget->setAspectRatioMode(Qt::KeepAspectRatio);

    //通过清单进行设备选择
    connect(ui->deviceChooseView,&QTableView::doubleClicked,this,&Device_Console::ChangeDevicePage);

    //进行套接字连接
    connect(this,&Device_Console::s_connectDeviceSockfd,device_TCP,&TCP_Thread::ConnectToServer);
    connect(this,&Device_Console::s_connectAlarmSockfd,alarm_TCP,&TCP_Thread::ConnectToServer);
    connect(this,&Device_Console::s_connectMediaSockfd,media_TCP,&TCP_Thread::ConnectToServer);

    //device_TCP连接成功后进行清单获取
    connect(device_TCP,&TCP_Thread::s_connectSuccess,this,&Device_Console::SendQueryMsg);

    //向TCP线程发送数据包，并使其发送至服务器
    connect(this,&Device_Console::s_sendMsgToDevice,device_TCP,&TCP_Thread::SendMsg);
    connect(this,&Device_Console::s_sendMsgToAlarm,alarm_TCP,&TCP_Thread::SendMsg);
    connect(this,&Device_Console::s_sendMsgToMedia,media_TCP,&TCP_Thread::SendMsg);

    //接收TCP线程返回的数据包
    connect(device_TCP,&TCP_Thread::s_recvMsg,this,&Device_Console::RecvDeviceMsg);
    connect(alarm_TCP,&TCP_Thread::s_recvMsg,this,&Device_Console::RecvAlarmMsg);
    connect(media_TCP,&TCP_Thread::s_recvMsg,this,&Device_Console::RecvMediaMsg);

    //接受线程返回错误
    connect(device_TCP,&TCP_Thread::s_wrongMsg,this,&Device_Console::WrongBox);

    //关闭线程TCP
    connect(this,&Device_Console::s_closeSockfd,device_TCP,&TCP_Thread::CloseTCP);
    connect(this,&Device_Console::s_Logout,device_TCP,&TCP_Thread::CloseTCP);
    connect(this,&Device_Console::s_closeSockfd,alarm_TCP,&TCP_Thread::CloseTCP);
    connect(this,&Device_Console::s_Logout,alarm_TCP,&TCP_Thread::CloseTCP);
    connect(this,&Device_Console::s_closeSockfd,media_TCP,&TCP_Thread::CloseTCP);
    connect(this,&Device_Console::s_Logout,media_TCP,&TCP_Thread::CloseTCP);

    //结束线程
    connect(this,&Device_Console::destroyed,this,[=](){
        deviceThread->quit();
        alarmThread->quit();
        mediaThread->quit();
        deviceThread->wait();
        MYLOG << "deviceThread线程：结束完毕";
        alarmThread->wait();
        MYLOG << "alarmThread线程：结束完毕";
        mediaThread->wait();
        MYLOG << "mediaThread线程：结束完毕";
        delete mediaThread;
        delete deviceThread;
        delete alarmThread;
    });

}

Device_Console::~Device_Console()
{
    delete refPlayer;
    delete refVideoWidget;
    delete device_TCP;
    delete alarm_TCP;
    delete media_TCP; 
    delete ui;
}

//错误提示窗口
void Device_Console::WrongBox(QString title,QString word)
{
    QMessageBox::warning(this,title,word);
}

//初始化
void Device_Console::DoInit(char *name)
{

    g_bGetAllStateFlag = false;
    memset(g_cUserName,0X0,NAME_PASSWORD_LEN);
    strcpy(g_cUserName,name);

    memset(g_cNowDeviceMac,0X0,32*sizeof (char));
    g_iGetDeviceNum = 0;
    g_iNowDeviceNum = 0;
    ui->stackedWidget->setCurrentIndex(0);
    deviceListModel->clear();
    MYLOG << g_cUserName <<" Login";
    emit s_connectDeviceSockfd(QString(SERVER_MASTER_IP),qint16(SERVER_DEVICE_PORT));
    emit s_connectAlarmSockfd(QString(SERVER_MASTER_IP),qint16(SERVER_ALARM_PORT));
    emit s_connectMediaSockfd(QString(SERVER_MASTER_IP),qint16(SERVER_MEDIA_PORT));
}

//接收deviceServer数据包
void Device_Console::RecvDeviceMsg(QVariant v_msg)
{
    MsgStruct recvMsg = v_msg.value<MsgStruct>();
    //确定包类型
    switch (recvMsg.data_type)
    {
    case MSG_DATA_QUERY_DEVICE:
        TakeQueryMsg(recvMsg);
        break;
    case MSG_DATA_ADD_DEVICE:
        TakeAddDeviceMsg(recvMsg);
        break;
    case MSG_DATA_GET_DEVICE_STATUS:
        TakeGetStatusMsg(recvMsg);
        break;
    case MSG_DATA_SET_DEVICE_STATUS:
        TakeSetStatusMsg(recvMsg);
        break;
    default:
        WrongBox(QString("DeviceMsg failed"),QString("data_type error:%1").arg(recvMsg.data_type));
        break;
    }
}

//接收alarmServer数据包
void Device_Console::RecvAlarmMsg(QVariant v_msg)
{
    MsgStruct recvMsg = v_msg.value<MsgStruct>();
    //确定包类型
    switch (recvMsg.data_type)
    {
    case MSG_DATA_DEVICE_ALARM_NOTIFY:
        TakeAlarmMsg(recvMsg);
        break;
    case MSG_DATA_GET_ALARM_NOTICE:
        TakeGetAlarmMsg(recvMsg);
        break;
    default:
        WrongBox(QString("AlarmMsg failed"),QString("data_type error:%1").arg(recvMsg.data_type));
        break;
    }
}

//接收mediaServer数据包
void Device_Console::RecvMediaMsg(QVariant v_msg)
{
    MsgStruct recvMsg = v_msg.value<MsgStruct>();
    //确定包类型
    switch (recvMsg.data_type)
    {
    case MSG_DATA_GET_PROXY_URL:
        TakeGetURLMsg(recvMsg);
        break;

    default:
        WrongBox(QString("MediaMsg failed"),QString("data_type error:%1").arg(recvMsg.data_type));
        break;
    }
}

//发送查询设备消息
void Device_Console::SendQueryMsg()
{
    SendMsgToDevice(MSG_DATA_QUERY_DEVICE, -1, strlen(g_cUserName), 0, MSG_HEADER_STABLE_LEN+strlen(g_cUserName),g_cUserName);
}

//处理设备报警通知
void Device_Console::TakeAlarmMsg(MsgStruct recvMsg)
{
    MYLOG << recvMsg.data;
    QString notic;
    if(strcmp(recvMsg.data,g_cNowDeviceMac) == 0)
    {
        MYLOG <<"SS" << recvMsg.custom1 << recvMsg.custom2;
        if(recvMsg.custom1 == 0)
        {
            switch (recvMsg.custom2) {
            case 0:
                notic = "无人时空调未关";
                break;
            case 1:
                notic = "温度设置异常";
                break;
            default:
                notic = "unknow type";
                break;
            }
            airAlarmModel->insertRow(0,new QStandardItem(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+" "+notic));
        }else if(recvMsg.custom1 == 1 )
        {
            switch (recvMsg.custom2) {
            case 0:
                notic = "食物余量预警";
                break;
            case 1:
                notic = "保鲜温度异常";
                break;
            case 2:
                notic = "冷冻温度异常";
                break;
            default:
                notic = "unknow type";
                break;
            }
            refAlarmModel->insertRow(0,new QStandardItem(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+" "+notic));
        }
    }

}

//处理获取设备报警结果
void Device_Console::TakeGetAlarmMsg(MsgStruct recvMsg)
{
    if (recvMsg.custom1 == MSG_CUSTOM1_GET_ALARM_NOTICE_FAILURE)
    {
        switch (recvMsg.custom2)
        {
        case MSG_CUSTOM2_GET_ALARM_NOTICE_ACCOUNT:
        {
            WrongBox(QString("失败"),QString("account error."));
            break;
        }
        case MSG_CUSTOM2_GET_ALARM_NOTICE_CONNECT:
        {
            WrongBox(QString("失败"),QString("connect error."));
            break;
        }
        case MSG_CUSTOM2_GET_ALARM_NOTICE_DATABASE:
        {
            WrongBox(QString("失败"),QString("database error."));
            break;
        }
        default: break;
        }
    }
    else if (recvMsg.custom1 == MSG_CUSTOM1_GET_ALARM_NOTICE_SUCCESS)
    {
        int noticeNum = recvMsg.custom2;
        for(int i=0; i<noticeNum; i++)
        {
            char buffer[50] = {0};
            QString notic;
            int noticeLen = 43;
            int macLen = 23;
            memcpy(buffer, recvMsg.data+noticeLen*i+macLen, noticeLen-macLen);
            if(g_cNowDeviceMac[1] == '1')
            {
                switch (buffer[noticeLen-macLen-1]) {
                case '0':
                    notic = "无人时空调未关";
                    break;
                case '1':
                    notic = "温度设置异常";
                    break;
                default:
                    notic = "unknow type";
                    break;
                }
                airAlarmModel->appendRow(new QStandardItem(QString(buffer).left(19)+" "+notic));
            }else if(g_cNowDeviceMac[1] == '2')
            {
                switch (buffer[noticeLen-macLen-1]) {
                case '0':
                    notic = "食物余量预警";
                    break;
                case '1':
                    notic = "保鲜温度异常";
                    break;
                case '2':
                    notic = "冷冻温度异常";
                    break;
                default:
                    notic = "unknow type";
                    break;
                }
                refAlarmModel->appendRow(new QStandardItem(QString(buffer).left(19)+" "+notic));
            }
        }
    }

}

//处理deviceServer查询设备结果
void Device_Console::TakeQueryMsg(MsgStruct recvMsg)
{
    if(recvMsg.custom1 == MSG_CUSTOM1_QUERY_DEVICE_SUCCESS)
    {
        g_iGetDeviceNum = recvMsg.custom2;
        //分析获得设备清单
        AnalyseDeviceList(recvMsg.data);
    }
    else if(recvMsg.custom1 == MSG_CUSTOM1_QUERY_DEVICE_FAILURE)
    {
        WrongBox("失败","Sorry！Failed to query device-names:");
        switch (recvMsg.custom2)
        {
        case MSG_CUSTOM2_QUERY_DEVICE_FAILURE_ACCOUNT:
            WrongBox("失败","Wrong account.");
            break;
        case MSG_CUSTOM2_QUERY_DEVICE_FAILURE_CONNECT:
            WrongBox("失败","Abnormal connection.");
            break;
        case MSG_CUSTOM2_QUERY_DEVICE_FAILURE_DATABASE:
            WrongBox("失败","Database exception.");
            break;
        default:
            WrongBox("失败","unknow reason");
            break;
        }
    }
    else
    {
        WrongBox("失败","Return unknow status");
    }
}

//处理deviceServer添加设备结果
void Device_Console::TakeAddDeviceMsg(MsgStruct recvMsg)
{
    if(recvMsg.custom1 == MSG_CUSTOM1_ADD_DEVICE_SUCCESS)
    {
        QString mac = QString(QLatin1String(recvMsg.data));
        AddDeviceList(mac);
        WrongBox(QString("add success"),QString("New device added successfully!"));
    }
    else if(recvMsg.custom1 == MSG_CUSTOM1_ADD_DEVICE_FAILURE)
    {
        switch (recvMsg.custom2)
        {
        case MSG_CUSTOM2_ADD_DEVICE_FAILURE_MACADDR:
            WrongBox(QString("add fail"),QString("Wrong mac address"));
            break;
        case MSG_CUSTOM2_ADD_DEVICE_FAILURE_ALREADY:
            WrongBox(QString("add fail"),QString("Device has been added"));
            break;
        case MSG_CUSTOM2_ADD_DEVICE_FAILURE_CONNECT:
            WrongBox(QString("add fail"),QString("Abnormal connection"));
            break;
        case MSG_CUSTOM2_ADD_DEVICE_FAILURE_DATABASE:
            WrongBox(QString("add fail"),QString("Database exception"));
            break;
        case MSG_CUSTOM2_ADD_DEVICE_FAILURE_DEVICE:
            WrongBox(QString("add fail"),QString("Abnormal device"));
            break;
        default:
            WrongBox(QString("add fail"),QString("unknow reason:%1").arg(recvMsg.custom2));
            break;
        }
    }
    else
    {
        WrongBox(QString("add fail"),QString("Return unknow status:%1").arg(recvMsg.custom1));
    }
    SendQueryMsg();
    ui->stackedWidget->setCurrentIndex(0);
}

//处理deviceServer设置状态结果
void Device_Console::TakeSetStatusMsg(MsgStruct recvMsg)
{
    if (recvMsg.custom1 == MSG_CUSTOM1_SET_DEVICE_STATUS_SUCCESS)
    {
        WrongBox(QString("success"),QString("set success"));
        switch (g_cNowDeviceMac[1])
        {
        case '1':
            SendMsgToDevice(MSG_DATA_GET_DEVICE_STATUS, -1, MSG_CUSTOM1_GET_DEVICE_AIRCONDITION, g_iDeviceStateType, MSG_HEADER_STABLE_LEN,g_cNowDeviceMac);
            break;
        case '2':
            SendMsgToDevice(MSG_DATA_GET_DEVICE_STATUS, -1, MSG_CUSTOM1_GET_DEVICE_REFRIGERATOR, g_iDeviceStateType, MSG_HEADER_STABLE_LEN,g_cNowDeviceMac);

            break;
        default: break;
        }
    }
    else if (recvMsg.custom1 == MSG_CUSTOM1_GET_DEVICE_STATUS_FAILURE)
    {
        switch (recvMsg.custom2)
        {
        case MSG_CUSTOM2_GET_DEVICE_STATUS_FAILURE_MACADDR:
            WrongBox(QString("get fail"),QString("macaddr error"));
            break;
        case MSG_CUSTOM2_GET_DEVICE_STATUS_FAILURE_COMMAND:
            WrongBox(QString("get fail"),QString("command error"));
            break;
        case MSG_CUSTOM2_GET_DEVICE_STATUS_FAILURE_CONNECT:
            WrongBox(QString("get fail"),QString("connect error"));
            break;
        case MSG_CUSTOM2_GET_DEVICE_STATUS_FAILURE_DEVICE :
            WrongBox(QString("get fail"),QString("device error"));
            break;
        default: break;
        }
    }

}

//处理deviceServer获取状态结果
void Device_Console::TakeGetStatusMsg(MsgStruct recvMsg)
{
    if (recvMsg.custom1 == MSG_CUSTOM1_GET_DEVICE_STATUS_SUCCESS)
    {
        switch (g_cNowDeviceMac[1])
        {
        case '1':
        {
            switch (g_iDeviceStateType)
            {
            case MSG_CUSTOM2_GET_DEVICE_AIR_ONOFF:
                ui->labelShow_switch->setText(QString(recvMsg.data));
                if(g_bGetAllStateFlag)
                {
                    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_AIR_HOTCOLD;
                    SendMsgToDevice(MSG_DATA_GET_DEVICE_STATUS, -1, MSG_CUSTOM1_GET_DEVICE_AIRCONDITION, MSG_CUSTOM2_GET_DEVICE_AIR_HOTCOLD, MSG_HEADER_STABLE_LEN,g_cNowDeviceMac);
                }
                break;
            case MSG_CUSTOM2_GET_DEVICE_AIR_HOTCOLD:
                ui->labelShow_mode->setText(QString(recvMsg.data));
                if(g_bGetAllStateFlag)
                {
                    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_AIR_TEMP;
                    SendMsgToDevice(MSG_DATA_GET_DEVICE_STATUS, -1, MSG_CUSTOM1_GET_DEVICE_AIRCONDITION, MSG_CUSTOM2_GET_DEVICE_AIR_TEMP, MSG_HEADER_STABLE_LEN,g_cNowDeviceMac);
                }
                break;
            case MSG_CUSTOM2_GET_DEVICE_AIR_TEMP:
                ui->labelShow_temp->setText(QString(recvMsg.data));
                if(g_bGetAllStateFlag)
                {
                    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_AIR_WIND;
                    SendMsgToDevice(MSG_DATA_GET_DEVICE_STATUS, -1, MSG_CUSTOM1_GET_DEVICE_AIRCONDITION, MSG_CUSTOM2_GET_DEVICE_AIR_WIND, MSG_HEADER_STABLE_LEN,g_cNowDeviceMac);
                }
                break;
            case MSG_CUSTOM2_GET_DEVICE_AIR_WIND:
                ui->labelShow_wind->setText(QString(recvMsg.data));
                if(g_bGetAllStateFlag)
                {
                    g_bGetAllStateFlag = false;
                }
                break;
            default: break;
            }
        } break;
        case '2':
        {
            switch (g_iDeviceStateType)
            {
            case MSG_CUSTOM2_GET_DEVICE_REF_FRESH:
                ui->labelShow_fresh->setText(QString(recvMsg.data));
                if(g_bGetAllStateFlag)
                {
                    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_REF_FREEZ;
                    SendMsgToDevice(MSG_DATA_GET_DEVICE_STATUS, -1, MSG_CUSTOM1_GET_DEVICE_REFRIGERATOR, MSG_CUSTOM2_GET_DEVICE_REF_FREEZ, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac);
                }
                break;
            case MSG_CUSTOM2_GET_DEVICE_REF_FREEZ:
                ui->labelShow_freeze->setText(QString(recvMsg.data));
                if(g_bGetAllStateFlag)
                {
                    g_bGetAllStateFlag = false;
                }
                break;
            default: break;
            }
        } break;
        default: break;
        }
        return;
    }else if (recvMsg.custom1 == MSG_CUSTOM1_GET_DEVICE_STATUS_FAILURE)
    {
        switch (recvMsg.custom2)
        {
        case MSG_CUSTOM2_GET_DEVICE_STATUS_FAILURE_MACADDR:
            WrongBox(QString("get fail"),QString("macaddr error"));
            break;
        case MSG_CUSTOM2_GET_DEVICE_STATUS_FAILURE_COMMAND:
            WrongBox(QString("get fail"),QString("command error"));
            break;
        case MSG_CUSTOM2_GET_DEVICE_STATUS_FAILURE_CONNECT:
            WrongBox(QString("get fail"),QString("connect error"));
            break;
        case MSG_CUSTOM2_GET_DEVICE_STATUS_FAILURE_DEVICE :
            WrongBox(QString("get fail"),QString("device error"));
            break;
        default: break;
        }
    }
}

//处理deviceServer获取状态结果
void Device_Console::TakeGetURLMsg(MsgStruct recvMsg)
{
    if (recvMsg.custom1 == MSG_CUSTOM1_GET_PROXY_URL_FAILURE) {
            switch (recvMsg.custom2) {
                case MSG_CUSTOM2_GET_PROXY_URL_ACCOUNT: {
                    printf("user don't login.\n");
                    WrongBox(QString("open fail"),QString("user don't login"));
                    } break;
                case MSG_CUSTOM2_GET_PROXY_URL_CONNECT: {
                    printf("connect error.\n");
                    WrongBox(QString("open fail"),QString("connect error"));
                    } break;
                case MSG_CUSTOM2_GET_PROXY_URL_DATABASE: {
                    printf("device error.\n");
                    WrongBox(QString("open fail"),QString("device error"));
                    } break;
                default: break;
            }
        }
        if (recvMsg.custom1 == MSG_CUSTOM1_GET_PROXY_URL_SUCCESS && strlen(recvMsg.data)) {
            MYLOG << recvMsg.data;
            //refPlayer->setMedia(QUrl::fromLocalFile("/mnt/hgfs/code/test1.mp4"));
            refPlayer->setMedia(QUrl(recvMsg.data));
            refPlayer->play();
        }
}

//分析获得设备清单
void Device_Console::AnalyseDeviceList(char *allDeviceMac)
{
    deviceListModel->clear();
    g_iNowDeviceNum = 0;
    for (int i = 0; i < g_iGetDeviceNum; i++) {
        char deviceMac[32] = {0};
        for (int j = 0; j < 23; j++) {
            deviceMac[j] = allDeviceMac[i * 23 + j];
        }
        QString str = QString(QLatin1String(deviceMac));
        AddDeviceList(str);
    }
}

//设备清单添加
void Device_Console::AddDeviceList(QString mac)
{
    //写入清单
    deviceListModel->setItem(g_iNowDeviceNum,1,new QStandardItem(mac));
    if(mac.at(1) == '1'){
        deviceListModel->setItem(g_iNowDeviceNum,0,new QStandardItem(QString("空调")));
    }else if(mac.at(1) == '2')
    {
        deviceListModel->setItem(g_iNowDeviceNum,0,new QStandardItem(QString("冰箱")));
    }else {
        deviceListModel->setItem(g_iNowDeviceNum,0,new QStandardItem(QString("未知")));
    }
    g_iNowDeviceNum++;
}

//双击清单切换控制台
void Device_Console::ChangeDevicePage(const QModelIndex &r)
{

    QModelIndex temp = deviceListModel->index(r.row(),1);
    QByteArray index = temp.data().toByteArray();
    memset(g_cNowDeviceMac,0x0,sizeof(char)*32);
    strcpy(g_cNowDeviceMac,index.data());//保存全局变量，确定当前控制台界面设备mac
    QString DeviceMac = temp.data().toString();
    if(DeviceMac.at(1) == "1"){
        ui->stackedWidget->setCurrentIndex(2);
        ui->label_mac->setText(DeviceMac);
    }else if(DeviceMac.at(1) == "2"){
        ui->stackedWidget->setCurrentIndex(3);
        ui->label_mac_3->setText(DeviceMac);
    }
    airAlarmModel->clear();
    refAlarmModel->clear();
}

//发送数据包至TCP线程
void Device_Console::SendMsgToDevice(int commandType, int curSeq, int custom1, int custom2, int total_len, char *data1,...)
{
    va_list CustomArg;
    va_start(CustomArg, data1);
    MsgStruct sendMsg;
    sendMsg.version = MSG_VERSION;
    sendMsg.header_len = MSG_HEADER_STABLE_LEN;
    sendMsg.encrypt_type = MSG_ENCRYPT_NONE;
    sendMsg.protocol_type = MSG_PROTOCOL_C2S;
    sendMsg.total_len = total_len;
    sendMsg.data_type = commandType;
    sendMsg.seq_num = curSeq;//置为0表示不需核验，若为其他则子线程重新计算赋值
    sendMsg.frag_flag = MSG_FLAG_FRAG_NO;
    sendMsg.frag_offset = 0;
    sendMsg.custom1 = custom1;
    sendMsg.custom2 = custom2;
    //sendMsg.header_chk由子线程计算
    sendMsg.source_addr = 0x7F000001;
    sendMsg.target_addr = 0x7F000001;
    strcpy(sendMsg.data, data1);
    char *dataTmp = (char *)va_arg(CustomArg, char *);
    if(dataTmp != NULL)
    {
        printf("dataTmp is %s.\n", dataTmp);
        strcat(sendMsg.data, dataTmp);
    }

//    strcat(sendMsg.data,(char *)va_arg(CustomArg, char *));
    va_end(CustomArg);
    QVariant emitToChildMsg;
    emitToChildMsg.setValue(sendMsg);
    emit s_sendMsgToDevice(emitToChildMsg);
}

void Device_Console::SendMsgToAlarm(int commandType, int curSeq, int custom1, int custom2, int total_len, char *data1,...)
{
    va_list CustomArg;
    va_start(CustomArg, data1);
    MsgStruct sendMsg;
    sendMsg.version = MSG_VERSION;
    sendMsg.header_len = MSG_HEADER_STABLE_LEN;
    sendMsg.encrypt_type = MSG_ENCRYPT_NONE;
    sendMsg.protocol_type = MSG_PROTOCOL_C2S;
    sendMsg.total_len = total_len;
    sendMsg.data_type = commandType;
    sendMsg.seq_num = curSeq;//置为0表示不需核验，若为其他则子线程重新计算赋值
    sendMsg.frag_flag = MSG_FLAG_FRAG_NO;
    sendMsg.frag_offset = 0;
    sendMsg.custom1 = custom1;
    sendMsg.custom2 = custom2;
    //sendMsg.header_chk由子线程计算
    sendMsg.source_addr = 0x7F000001;
    sendMsg.target_addr = 0x7F000001;
    strcpy(sendMsg.data, data1);
    strcat(sendMsg.data,(char *)va_arg(CustomArg, char *));
    va_end(CustomArg);
    QVariant emitToChildMsg;
    emitToChildMsg.setValue(sendMsg);
    emit s_sendMsgToAlarm(emitToChildMsg);
}

void Device_Console::SendMsgToMedia(int commandType, int curSeq, int custom1, int custom2, int total_len, char *data1,...)
{
    va_list CustomArg;
    va_start(CustomArg, data1);
    MsgStruct sendMsg;
    sendMsg.version = MSG_VERSION;
    sendMsg.header_len = MSG_HEADER_STABLE_LEN;
    sendMsg.encrypt_type = MSG_ENCRYPT_NONE;
    sendMsg.protocol_type = MSG_PROTOCOL_C2S;
    sendMsg.total_len = total_len;
    sendMsg.data_type = commandType;
    sendMsg.seq_num = curSeq;//置为0表示不需核验，若为其他则子线程重新计算赋值
    sendMsg.frag_flag = MSG_FLAG_FRAG_NO;
    sendMsg.frag_offset = 0;
    sendMsg.custom1 = custom1;
    sendMsg.custom2 = custom2;
    //sendMsg.header_chk由子线程计算
    sendMsg.source_addr = 0x7F000001;
    sendMsg.target_addr = 0x7F000001;
    strcpy(sendMsg.data, data1);
    strcat(sendMsg.data,(char *)va_arg(CustomArg, char *));
    va_end(CustomArg);
    MYLOG << sendMsg.data;
    QVariant emitToChildMsg;
    emitToChildMsg.setValue(sendMsg);
    emit s_sendMsgToMedia(emitToChildMsg);
}

//主页面按键槽函数
void Device_Console::on_homePushButton_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

//添加设备按键槽函数
void Device_Console::on_addpushButton_clicked()
{
    ui->addDeviceLabel->setText("请打开未注册设备，并连接至服务器进行添加");
    ui->stackedWidget->setCurrentIndex(1);
    SendMsgToDevice(MSG_DATA_ADD_DEVICE, -1, strlen(g_cUserName), 0, MSG_HEADER_STABLE_LEN+strlen(g_cUserName),g_cUserName);
}

//获取设备数据按键槽函数
void Device_Console::on_pushButton_getAirStatuse_clicked()
{
    g_bGetAllStateFlag = true;
    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_AIR_ONOFF;
    SendMsgToDevice(MSG_DATA_GET_DEVICE_STATUS, -1, MSG_CUSTOM1_GET_DEVICE_AIRCONDITION, MSG_CUSTOM2_GET_DEVICE_AIR_ONOFF, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac);
}

void Device_Console::on_pushButton_getRefStatuse_clicked()
{
    g_bGetAllStateFlag = true;
    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_REF_FRESH;
    SendMsgToDevice(MSG_DATA_GET_DEVICE_STATUS, -1, MSG_CUSTOM1_GET_DEVICE_REFRIGERATOR, MSG_CUSTOM2_GET_DEVICE_REF_FRESH, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac);
}

//设置设备数据按键槽函数
void Device_Console::on_pushButton_switchSet_clicked()
{
    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_AIR_ONOFF;
    switch (buttonGroupSwitch->checkedId()) {
    case 0:
        SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_AIRCONDITION, MSG_CUSTOM2_SET_DEVICE_AIR_ON, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,"on");
        break;
    case 1:
        SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_AIRCONDITION, MSG_CUSTOM2_SET_DEVICE_AIR_OFF, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,"off");
        break;
    }
}

void Device_Console::on_pushButton_modeSet_clicked()
{
    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_AIR_HOTCOLD;
    switch (buttonGroupMode->checkedId()) {
    case 0:
        SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_AIRCONDITION, MSG_CUSTOM2_SET_DEVICE_AIR_COLD, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,"cold");
        break;
    case 1:
        SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_AIRCONDITION, MSG_CUSTOM2_SET_DEVICE_AIR_HOT, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,"hot");
        break;
    }
}

void Device_Console::on_pushButton_windSet_clicked()
{
    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_AIR_WIND;
    switch (buttonGroupWind ->checkedId()) {
    case 0:
        SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_AIRCONDITION, MSG_CUSTOM2_SET_DEVICE_AIR_WIND, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,"low");
        break;
    case 1:
        SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_AIRCONDITION, MSG_CUSTOM2_SET_DEVICE_AIR_WIND, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,"midlle");
        break;
    case 2:
        SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_AIRCONDITION, MSG_CUSTOM2_SET_DEVICE_AIR_WIND, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,"high");
        break;
    }
}

void Device_Console::on_pushButton_tempSet_clicked()
{
    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_AIR_TEMP;
    QString str =QString::number(ui->spinBox_temp->value());
    char* index;
    QByteArray ba = str.toLatin1();
    index=ba.data();
    MYLOG << index;
    SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_AIRCONDITION, MSG_CUSTOM2_SET_DEVICE_AIR_TEMP,MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,index);
}

void Device_Console::on_pushButton_freezeTempSet_clicked()
{
    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_REF_FREEZ;
    QString str =QString::number(ui->spinBox_freezeTemp->value());
    char* index;
    QByteArray ba = str.toLatin1();
    index=ba.data();
    MYLOG << index;
    SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_REFRIGERATOR, MSG_CUSTOM2_SET_DEVICE_REF_FREEZ,MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,index);
}

void Device_Console::on_pushButton_freshTempSet_clicked()
{
    g_iDeviceStateType = MSG_CUSTOM2_GET_DEVICE_REF_FRESH;
    QString str =QString::number(ui->spinBox_freshTemp->value());
    char* index;
    QByteArray ba = str.toLatin1();
    index=ba.data();
    SendMsgToDevice(MSG_DATA_SET_DEVICE_STATUS, -1, MSG_CUSTOM1_SET_DEVICE_REFRIGERATOR, MSG_CUSTOM2_SET_DEVICE_REF_FRESH, MSG_HEADER_STABLE_LEN, g_cNowDeviceMac,index);
}

void Device_Console::on_pushButton_airAlarmGet_clicked()
{
    int custom1 =strlen(g_cUserName);
    int custom2 = 0xFF;
    int total_len = MSG_HEADER_STABLE_LEN + custom1 + strlen(g_cNowDeviceMac);
    airAlarmModel->clear();
    SendMsgToAlarm(MSG_DATA_GET_ALARM_NOTICE, -1, custom1, custom2, total_len, g_cUserName ,g_cNowDeviceMac);
}

void Device_Console::on_pushButton_airAlarmClear_clicked()
{
    airAlarmModel->clear();
}

void Device_Console::on_pushButton_refAlarmGet_clicked()
{
    int custom1 =strlen(g_cUserName);
    int custom2 = 0xFF;
    int total_len = MSG_HEADER_STABLE_LEN + custom1 + strlen(g_cNowDeviceMac);
    refAlarmModel->clear();
    SendMsgToAlarm(MSG_DATA_GET_ALARM_NOTICE, -1, custom1, custom2, total_len, g_cUserName ,g_cNowDeviceMac);
}

void Device_Console::on_pushButton_refAlarmClear_clicked()
{
    airAlarmModel->clear();
}

void Device_Console::on_pushButton_videoClose_clicked()
{

    refPlayer->stop();
    refPlayer->setMedia(NULL);
}

void Device_Console::on_pushButton_videoOpen_clicked()
{
    int custom1 =strlen(g_cUserName);
    int custom2 = 0xFF;
    int total_len = MSG_HEADER_STABLE_LEN;
    SendMsgToMedia(MSG_DATA_GET_PROXY_URL, -1, custom1, custom2, total_len, g_cUserName ,g_cNowDeviceMac);
}

//退出登陆按键槽函数
void Device_Console::on_logoutPushButton_clicked()
{
    emit s_Logout();

    this->hide();
}


//重写关闭事件，发送信号结束线程内TCP
void Device_Console::closeEvent(QCloseEvent *event)
{
    emit s_closeSockfd();
    while(1)
    {
        if(!device_TCP->g_bTcpStateFlag && !alarm_TCP->g_bTcpStateFlag && !media_TCP->g_bTcpStateFlag)
        {
            break;
        }
    }
    if(event){};//消除变量未使用警告
}
